package com.bookstore.servlet;

import com.bookstore.entity.Product;
import com.bookstore.service.ProductService;
import com.bookstore.service.impl.ProductServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/product.do")
public class ProductServlet extends BaseServlet {
    ProductService productService = new ProductServiceImpl();

    protected void queryAll(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        List<Product> products = productService.queryAllProducts();
        req.setAttribute("products", products);
        req.getRequestDispatcher("/admin/product_list.jsp").forward(req, resp);
    }

    protected void insert(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //获取前端传来的值
        String name = request.getParameter("name");
        Double price = Double.valueOf(request.getParameter("price"));
        //因为前端浏览器使用ISO-8859-1传参，所以在后端需要使用 ISO-8859-1 将字符转换成数字，再将 数字用UTF-8编码转成中文字符
        String category = new String(request.getParameter("category").getBytes("ISO-8859-1"), "UTF-8");
        Integer pNum = Integer.valueOf(request.getParameter("pNum"));
        String imgUrl = request.getParameter("imgUrl");
        String description = new String(request.getParameter("description").getBytes("ISO-8859-1"), "UTF-8");
        int result = productService.insertProduct(new Product(null, name, price, category, pNum, imgUrl, description));
        //直接跳转回商品查询界面
        response.sendRedirect("./product.do?action=queryAll");
    }

    protected void delete(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Long id = Long.parseLong(request.getParameter("id"));
        int result = productService.deleteProduct(id);
        //直接跳转回商品查询界面
        response.sendRedirect("./product.do?action=queryAll");
    }

    protected void update(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //获取前端传来的值
        Long id = Long.parseLong(request.getParameter("id"));
        String name = request.getParameter("name");
        Double price = Double.valueOf(request.getParameter("price"));
        //因为前端浏览器使用ISO-8859-1传参，所以在后端需要使用 ISO-8859-1 将字符转换成数字，再将 数字用UTF-8编码转成中文字符
        String category = new String(request.getParameter("category").getBytes("ISO-8859-1"), "UTF-8");
        Integer pNum = Integer.valueOf(request.getParameter("pNum"));
        String imgUrl = request.getParameter("imgUrl");
        String description = new String(request.getParameter("description").getBytes("ISO-8859-1"), "UTF-8");
        int result = productService.updateProduct(new Product(id, name, price, category, pNum, imgUrl, description));
        //直接跳转回商品查询界面
        response.sendRedirect("./product.do?action=queryAll");
    }
}
